<?php

namespace App\Repository;

use App\Common\Libs\ArrayHelper;
use App\Common\Libs\IdBuilder;
use App\Consts\GlobalConst;
use App\Models\UserBrowseHistory;

/**
 * Class BrowseHistoryRepository
 * @package App\Repository
 */
class BrowseHistoryRepository extends BaseRepository
{

    /**
     * @param $loadData
     * @return bool
     */
    public function create($loadData)
    {
        $query = UserBrowseHistory::getModel($loadData['user_id']);
        $dayStartTime = strtotime(date('Y-m-d'));

        $browseHistory = $query
            ->whereBetween('updated_at', [$dayStartTime, $dayStartTime + 86400])
            ->where('target_id', $loadData['target_id'])
            ->where('user_id', $loadData['user_id'])
            ->first();

        if ($browseHistory) {
            $browseHistory->update([
                'updated_at' => time(),
            ]);

            return $browseHistory;
        }

        $loadData = ArrayHelper::merge($loadData, [
            'history_id' => IdBuilder::getUniqueID(),
            'is_deleted' => GlobalConst::IS_NOT_DELETE,
            'created_at' => time(),
            'updated_at' => time(),
        ]);

        return $query->create($loadData);
    }

}
